#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <cstdio>
#include <cerrno>
#include <signal.h>
#include <cstring>

using namespace std;

void SetNonBlock(int fd)
{
    int cur_flag = fcntl(fd, F_GETFL);
    if (cur_flag < 0)
    {
        perror("fcntl - F_GETFL");
        return;
    }

    if (fcntl(fd, F_SETFL, cur_flag | O_NONBLOCK) < 0)
    {
        perror("fcntl - F_SETFL");
        return;
    }
    cout << "Set fd " << fd << " to non-blocking mode done" << endl;
}

int main()
{
    char buffer[1024];
    SetNonBlock(0);
    sleep(1);
    while (true)
    {
        printf("Please Enter# ");
        fflush(stdout);
        sleep(1);

        ssize_t n = read(0, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n - 1] = 0;
            cout << "echo : " << buffer << endl;
        }
        else if (n == 0)
        {
            cout << "read done" << endl;
            break;
        }
        else
        {
            // 设置为非阻塞 底层fd数据没有就绪 recv/read/write/send返回值以出错形式返回
            if (errno == EWOULDBLOCK || errno == EAGAIN)
            {
                cout << "No data available yet, trying again..." << endl;
                sleep(1);
                // do_other_thing();
            }
            else if (errno == EINTR)
            {
                cout << "Read interrupted by signal, retrying..." << endl;
            }
            else
            {
                // real 读取错误
                cerr << "read error, n = " << n << "errno code: "
                     << errno << ", error str: " << strerror(errno) << endl;
                break;
            }
        }
    }

    return 0;
}